package com.mrjy.common.controller;

import com.mrjy.common.entity.AccessLog;
import com.mrjy.common.entity.MenuInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.maintain.bo.IAccessLogBo;
import com.mrjy.maintain.dao.IMenuInfoDao;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@Controller
@RequestMapping("/common/util")
public class UtilController {
	
	@Autowired
	private IAccessLogBo accessLogBo;
	@Autowired
	private IMenuInfoDao menuInfoDao;

    /**
     * ajax 重定向
     */
    @RequestMapping("/ajaxRedirect")
    public Object ajaxRedirect() {
        System.out.println("3333333333");
        return new ModelAndView("redirect:/payment/pcPayment.jsp");
    }

	/**
	 * 文件上传
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public Object upload(MultipartFile uploadFile,HttpSession session,String fileSavePath,String fileSaveName) {
		String path = session.getServletContext().getRealPath(fileSavePath);
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		String originalFilename = uploadFile.getOriginalFilename();
		if(fileSaveName==null || "".equals(fileSaveName)){
			  fileSaveName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
		}
        File file = new File(path, fileSaveName);
        try {
        	uploadFile.transferTo(file);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return "ok_" + fileSaveName;
	}

	/**
	 * 获得服务器时间
	 */
	@RequestMapping("/serverTime")
	@ResponseBody
	public Object serverTime(){
		return new Date().getTime();
	}

	/**
	 * 退出系统
	 * 个人中心--退出登录
	 * @author csshui isUser= true
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public Object logout(HttpSession session,HttpServletRequest request){
		UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if (userInfo != null) {
			if (StringUtils.isNotBlank(userInfo.getLoginCode())) {
				request.getServletContext().removeAttribute(userInfo.getLoginCode());
			}

		}
		session.removeAttribute(GlobalConstant.USER_INFO);
		return "ok";
	}

	@RequestMapping("/getLocalIp")
	@ResponseBody
	public Object getLocalIp(HttpServletRequest request){

		String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户ip   
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        //客户端的IP地址
        String exter_invoke_ip = ip;
        System.out.println("客户端外网ip:"+exter_invoke_ip);

        return exter_invoke_ip;
	}

	@RequestMapping("/getRealIPs")
	@ResponseBody
	public List<String> getRealIPs(){
		List<String> ips = new ArrayList<String>();
		String localip = null;// 本地IP，如果没有配置外网IP则返回它
		String netip = null;// 外网IP
		Enumeration<NetworkInterface> netInterfaces;
		try {
		netInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
		return null;
		}
		InetAddress ip = null;
		boolean finded = false;// 是否找到外网IP
		while (netInterfaces.hasMoreElements() && !finded) {
		NetworkInterface ni = netInterfaces.nextElement();
		Enumeration<InetAddress> address = ni.getInetAddresses();
		while (address.hasMoreElements()) {
		ip = address.nextElement();
		if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
		netip = ip.getHostAddress();
		ips.add(netip);
		finded = true;
		break;
		} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
		localip = ip.getHostAddress();
		ips.add(localip);
		}
		}
		}
		return ips;
	}


}
